<?php
declare (strict_types=1);

namespace addons\V4\admin\model;

use app\common\model\Base;
use think\facade\Event;

class Product extends Base
{
    protected $name = 'addons_mall_product';

    public function cate1()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')->field('id,title');
    }

    public static function _save($param, $logs): array
    {
        parent::startTrans();
        try {
            if($param['cate_1'] > 1){
                if(empty($param['cate_2'])){
                    return ['code' => -1, 'msg' => '兑换专区商品必须选择二级分类'];
                }
            }
            if (isset($param['id']) && $param['id']) {
                $product = parent::update($param);
                $product->operation = 'save';
            } else {
                $product = parent::create($param);
                $product->operation = 'create';
            }
            if (!empty($param['spec_open'])) {
                $specData = $param['specData'];
                $skus = $param['skus'];
                //设置商品规格数据
                $result = ProductSpecData::setSpecData($product->id, $specData);
                if (!$result) {
                    parent::rollback();
                    return ['code' => -1, 'msg' => '加载失败，error:1'];
                }

                //设置商品规格值
                $result = ProductSpecValue::setSpecValue($product->id, $skus);
                if (!$result) {
                    parent::rollback();
                    return ['code' => -1, 'msg' => '加载失败，error:2'];
                }
                foreach ($result as $k => $v) {
                    $product->$k = $v;
                }

            }
            $product->save();

            parent::commit();
            Event::trigger('Logs', $product);
            return ['code' => 1, 'msg' => '已保存'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}
